from django.shortcuts import render, redirect

# Create your views here.
from django.urls import reverse
from django.views import View
from django.http.response import HttpResponseBadRequest, JsonResponse
import re
import logging
from apps.users.models import User
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.mixins import LoginRequiredMixin
import json

from apps.users.utils import LoginRequiredJSONMixin, email_secret, email_open
from utils.response_code import RETCODE
from django.core.mail import send_mail

logger = logging.getLogger('django')


# 注册
class Register(View):
    def get(self, request):
        return render(request, 'register.html')

    def post(self, request):
        # 接收数据
        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        phoneNumber = request.POST.get('phoneNumber')
        allow = request.POST.get('allow')
        print(username, password, password2, phoneNumber, allow)

        # 校验数据
        if not all([username, password, password2, phoneNumber, allow]):
            return HttpResponseBadRequest('参数不全')
        if not re.match(r'^[a-zA-Z0-9_-]{5,20}$', username):
            return HttpResponseBadRequest('用户名格式错误')
        if not re.match(r'^[a-zA-Z0-9]{8,20}$', password):
            return HttpResponseBadRequest('密码格式错误')
        if password != password2:
            return HttpResponseBadRequest('两次密码不一致')
        if not re.match(r'^1[3-8]\d{9}$', phoneNumber):
            return HttpResponseBadRequest('手机号格式不对')
        if not allow:
            return HttpResponseBadRequest('没有阅读协议')

        # 保存数据
        try:
            user = User.objects.create_user(
                username=username,
                password=password,
                mobile=phoneNumber
            )
        except Exception as e:
            logger.error(e)
            context = {
                "register_errmsg": "创建用户失败"
            }
            return render(request, 'register.html', context)

        # 保存用户状态
        login(request, user)

        # 页面跳转
        return redirect(reverse('contents:index'))


# 判断用户名是否重复
class Username(View):
    def get(self, request, username):
        count = User.objects.filter(username=username).count()
        return JsonResponse({"count": count})


# 登陆
class Login(View):
    def get(self, request):
        return render(request, 'login.html')

    def post(self, request):
        # 接受数据
        data = request.POST
        username = data.get('username')
        password = data.get('pwd')
        allow = data.get('remembered')

        # 校验用户数据格式
        if not all([username, password]):
            return HttpResponseBadRequest('参数不全')
        if re.match(r'^[a-zA-Z0-9]{5,20}/$', username):
            return HttpResponseBadRequest('用户名格式不对')
        if re.match(r'^[a-zA-Z0-9]{8,20}/$', password):
            return HttpResponseBadRequest('密码错误')
        # 校验用户数据是否存在
        user = authenticate(username=username, password=password)
        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户不存在'})

        # 记住登陆状态（添加用户session信息，默认为两周）
        login(request, user)

        # 是否记住用户(如果不记住，用户退出网站时就会清除session)
        if allow != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        next = request.GET.get('next')
        if next:
            response = redirect(next)
        else:
            response = redirect(reverse('contents:index'))

        # 在cookie添加username，用于前端用户判断
        if allow != 'on':
            response.set_cookie('username', username)
        else:
            response.set_cookie('username', username, 12 * 24 * 3600)

        return response


# 退出登陆
class Logout(View):
    def get(self, request):
        logout(request)

        response = redirect(reverse('contents:index'))
        response.delete_cookie('username')
        return response


# 用户中心
class Info(LoginRequiredMixin, View):
    def get(self, request):
        context = {
            'username': request.user.username,
            'mobile': request.user.mobile,
            'email': request.user.email,
            'email_active': request.user.email_active
        }
        return render(request, 'user_center_info.html', context)


# 发送邮件
class Emails(LoginRequiredJSONMixin, View):
    def put(self, request):
        # 接受数据
        data = request.body.decode()
        email = json.loads(data).get('email')

        # 校验数据
        if not re.match('^[a-z0-9][\w\.\-]*@[a-z0-9\-]+(\.[a-z]{2,5}){1,2}$', email):
            return JsonResponse({'code': RETCODE.PARAMERR, 'errmsg': '参数错误'})

        # 更新数据
        try:
            request.user.email = email
            request.user.save()
        except Exception as e:
            return JsonResponse({'code': RETCODE.DBERR, 'errmsg': '更新错误'})

        # 生成邮件链接
        verify_url = email_secret(request.user.id)

        # 发送邮件
        subject = '美多商城激活邮件'
        message = 'hello, i am meiduo'
        from_email = '美多商城<18327663086@163.com>'
        recipient_list = [email]
        html_message = '<p>您的邮箱为：%s 。请点击此链接激活您的邮箱：</p>' \
                       '<p><a href="%s">%s<a></p>' % (email, verify_url, verify_url)

        send_mail(
            subject=subject,
            message=message,
            from_email=from_email,
            recipient_list=recipient_list,
            html_message=html_message
        )

        # 返回响应
        return JsonResponse({'code': RETCODE.OK, 'errmsg': 'ok'})


# 激活用户邮箱
class CheckEmail(View):
    def get(self, request):
        token = request.GET.get('token')
        if token is None:
            return HttpResponseBadRequest('参数错误')
        if email_open(token) is None:
            return HttpResponseBadRequest('参数错误')

        try:
            user = User.objects.get(pk=email_open(token))
            if user is not None:
                user.email_active = True
                user.save()
        except Exception as e:
            return HttpResponseBadRequest('参数错误')

        return redirect(reverse('users:info'))


# 跳转我的地址
class Address(View):
    def get(self, request):
        return render(request, 'user_center_site.html')


# 新增地址
class AddressCreate(View):
    def post(self, request):
        pass

